const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "限时秒杀", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent'
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,

    openid: '',
    shareTitle: "",
    shareImg: '',
    flag: 0,
    ruleImg: '',
    prizeInfo: [],
    prizeName: '',

    // 假设的目标时间戳，这里以当前时间后的一周为例
    //targetTimestamp: new Date().getTime() + 7 * 24 * 60 * 60 * 1000,
    targetTimestamp: 0,
    days: 0,
    hours: 0,
    minutes: 0,
    seconds: 0,

    showGift: false,
    showGNotWinning: false, // 未中奖

    id: 0,
    activeStatus: 1, // -1:过了预约时间未到秒杀时间 0:未到预约时间 1:预约时间内 2：秒杀中(商品未被秒杀完)  3:秒杀结束
    headList: [], //头像列表
    prizeInfo: [], //秒杀商品信息
    activityInfo: [], //活动信息
    syPeople: 0, //剩余名额
    yyTotal: 0 //预约总人数
  },

  closevideo() {
    wx.navigateBack({
      delta: 1
    });
  },
  // 未中奖显示关闭
  regretBtn() {
    wx.switchTab({
      url: '/pages/index/index'
    });
    /*this.setData({
      showGNotWinning: !this.data.showGNotWinning
    })*/
  },

  //点击查看订单
  goBirthdayOrder() {
    var that = this;
    wx.navigateTo({
      url: '/pages/my/orderList?headerFlag=ms&id=' + that.data.id
    });
  },

  //点击抽奖
  cj() {
    var that = this;
    const now = new Date().getTime();
    const distance = this.data.targetTimestamp - now;

    if (that.data.activeStatus == 0) {
      app.showTip('此活动未到预约时间哦');
      return;
    }

    if (that.data.activeStatus == -1) {
      app.showTip('未到秒杀时间哦');
      return;
    }

    //判断活动状态
    if (that.data.activeStatus == 1 && distance > 0) {
      app.showTip('秒杀暂未开始哦');
      return;
    }
    //判断我是否中奖
    if (that.data.prizeInfo['id'] > 0) {
      that.setData({
        showGift: true
      });
      return;
    }

    //判断活动是否结束
    if (that.data.activeStatus == 3) {
      that.setData({
        showGNotWinning: true
      });
      return;
    }


    if (that.data.flag == 0) {
      that.setData({
        flag: 1
      });

      wx.showLoading({
        title: '秒杀中...',
        mask: true
      })
      var outTime = parseInt(that.getRandomArbitrary(100, 2000));
      console.log(outTime, 'outTime');
      //后台请求抽奖
      setTimeout(function () {
        wx.request({
          url: that.data.baseUrl + 'getSeckillPrize.php',
          method: 'POST',
          data: {
            openid: that.data.openid,
            id: that.data.id
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            setTimeout(function () {
              wx.hideLoading();
              if (res.data.status == 1) {
                that.setData({
                  prizeInfo: res.data.prizeInfo,
                  showGift: true
                });
              } else if (res.data.status == 100) {
                //秒杀结束
                that.setData({
                  showGNotWinning: true
                })
              } else {
                app.showTip(res.data.msg);
              }
              that.setData({
                flag: 0
              });
            }, 1300)
          },
          fail: function (res) {
            wx.hideLoading();
            app.showTip('服务器繁忙,请稍候重试');
            that.setData({
              flag: 0
            });
          }
        });
      }, outTime);
    }
  },

  //生成一个随机延迟请求的毫秒数
  getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
  },

  updateCountdown: function () {
    var that = this;
    const now = new Date().getTime();
    const distance = this.data.targetTimestamp - now;
    if (distance <= 0) {

      return
    }
    // 计算剩余时间
    let days = Math.floor(distance / (1000 * 60 * 60 * 24));
    let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    let seconds = Math.floor((distance % (1000 * 60)) / 1000);
    // 更新数据
    this.setData({
      days: days < 10 ? '0' + days : days,
      hours: hours < 10 ? '0' + hours : hours,
      minutes: minutes < 10 ? '0' + minutes : minutes,
      seconds: seconds < 10 ? '0' + seconds : seconds
    });
    if (days == 0 && hours == 0 && minutes == 0 && seconds == 0) {
      //最后一秒后重新刷新页面数据
      that.getSeckillPageInfo(that.data.openid, that.data.id);
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;

    var id = options.id;

    if (id == '' || id == '0') {
      app.showTip('抱歉,未获取到相关的id信息哦');
      setTimeout(function () {
        wx.navigateBack({
          delta: 1
        });
      }, 2000);
      return;
    }
    this.setData({
      id: id
    });

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getSeckillPageInfo(res.data.openid, id);

                //调用分享
                that.getShareInfo();
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //调用分享
      that.getShareInfo();

      //获取本页数据
      that.getSeckillPageInfo(openid, id);
    }
  },

  //获取本页数据
  getSeckillPageInfo(openid, id) {
    var that = this;
    /*wx.showLoading({
      title: '数据加载中...'
    })*/
    wx.request({
      url: that.data.baseUrl + 'getSeckillPageInfo.php',
      method: 'POST',
      data: {
        'openid': openid,
        'id': id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        //wx.hideLoading();
        if (res.data.status == 1) {
          //判断是否提示预约成功
          if (res.data.isShowYy == 1) {
            setTimeout(function () {
              that.selectComponent('#confirmTtips').openPop()
            }, 1000);
          }

          //判断我是否中奖过了
          if (parseInt(res.data.prizeInfo['id']) > 0) {
            //中奖过了 显示中奖框
            that.setData({
              showGift: true
            });
          } else {
            //未中奖过 判断活动是否结束
            if (res.data.activeStatus == 3) {
              //活动结束弹出结束框
              that.setData({
                showGNotWinning: true,
                activeStatus: 3
              });
            }
          }

          //重置其他参数值
          that.setData({
            activeStatus: res.data.activeStatus,
            headList: res.data.headList,
            prizeInfo: res.data.prizeInfo,
            activityInfo: res.data.activityInfo,
            syPeople: res.data.syPeople,
            yyTotal: res.data.yyTotal,
            prizeInfo: res.data.prizeInfo,
            shareTitle: res.data.activityInfo.title,
            shareImg: that.data.baseUrl + "admin/" + res.data.activityInfo.img_path,
            prizeName: res.data.prizeName
          });

          // 倒计时初始调用
          if (res.data.djsSjc > 0) {
            that.setData({
              targetTimestamp: res.data.djsSjc
            });
            that.updateCountdown();
            // 每隔一秒更新一次
            setInterval(() => {
              that.updateCountdown();
            }, 1000);
          }
        } else {
          app.showTip(res.data.msg);
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 2000);
        }
      },
      fail: function () {
        //wx.hideLoading();
        app.showTip('抱歉,服务器繁忙');
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          });
        }, 2000);
      }
    });
  },


  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/lotteryDrawPage/detail/index?id=' + that.data.id,
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})